package question5.com.qee.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.regex.Pattern;

/**
 * @ProjectName: learning
 * @Package: question5.com.qee.jdbc
 * @ClassName: ConnectionHolder
 * @Description:
 * @Date: 2021/10/20 5:00 下午
 * @Version: 1.0
 */
public class ConnectionHolder {

    //id=? and xxx =xxx
    protected static Pattern pattern = Pattern.compile("\\s*(\\w+)\\s*=\\s*");

    protected static String preOpTableName = "\\s*insert\\s*into\\s* \\w+\\s*";


    protected static String columnName = "\\s*(\\((\\s*\\w+\\s*,*\\s*)+\\))\\s*";


    protected static String batchValues = "values(\\s*\\((\\s*#\\{\\s*(\\w+)+\\s*},*\\s*)+\\)\\s*,*)+";


    protected static String getValue = "#\\{\\s*(\\w+)\\s*}";


    protected static Pattern insertPattern = Pattern.compile(preOpTableName + columnName + batchValues);

    protected static Pattern getValuePattern = Pattern.compile(getValue);

    protected static Pattern columnNamePattern = Pattern.compile(columnName);

    protected Connection connection;


    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static final String jdbcUrl = "jdbc:mysql://127.0.0.1:3306/test?useServerPrepStmts=true&zeroDateTimeBehavior=convertToNull&characterEncoding=utf8";


    public ConnectionHolder() {
        connection = createConnection();
    }

    public Connection createConnection() {
        try {
            connection = DriverManager.getConnection(jdbcUrl, "root", "root");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public void closeConnection() {
        try {
            connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }


    public Statement createStatement() {
        try {
            Statement statement = connection.createStatement();
            return statement;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Statement createStatement(String sql) {
        return createStatement();
    }


}
